<template>
  <div class="payment_center_account">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
          justify="start"
          class="search-item-left">
          <Col class="search-item">
            <span class="search-label">商户名称:</span>
            <Input v-model="accountName"
              placeholder="请输入"
              @on-keyup="filterSpace"></Input>
          </Col>
          <Col class="search-item">
            <span class="search-label">支付服务商:</span>
            <Select v-model="serviceName"
              @on-change="search">
              <Option v-for="item in serviceSelectNames"
                :value="item.value"
                :key="item.value">
                {{ item.label }}
              </Option>
            </Select>
          </Col>
          <Col class="search-item">
            <Button class="search-btn"
              type="primary"
              @click="search">查询</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn"
              @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
          justify="end"
          class="search-item-right">
          <Col class="search-item">
            <Button class="search-btn"
              type="primary"
              v-if="hasPermission('moms:pay:accountcreate')"
              @click="skipAdd">新增账号</Button>
          </Col>
          <Col class="search-item">
            <Button @click="addChildren"
              v-if="hasPermission('moms:pay:accountcreate')">新增微信子账号</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <Table
      :height="this.tableHeight"
      ref="expandTable"
      class="table-list"
      :loading="loading"
      :columns="columns"
      :row-class-name="rowClassName"
      @on-selection-change="selectionChange"
      :data="data">
      <template slot-scope="{ row, index }"
        slot="accountNo">
        <div class="table-icon-container" @click="expandRow(row, index)">
          <Icon :type="row.isExpand ? 'ios-arrow-down' : 'ios-arrow-forward'" :style="{ visibility: row.hasChildren ? 'visible' : 'hidden' }" class="table-icon" />
          <span>{{ row.accountNo }}</span>
        </div>
      </template>
      <template slot-scope="{ row }"
        slot="bankAccountType">
        <span>{{ getEnumsName(row.bankAccountType, accountTypes) }}</span>
      </template>
      <template slot-scope="{ row, index }"
        slot="action">
        <i class="iconsys icondetail"
          @click="look(row.paymentAccountId)"
          title="查看详情">
        </i>
        <i class="iconsys iconedit"
          title="编辑"
          v-if="hasPermission('moms:pay:accountupdate')"
          @click="skipEdit(row)"></i>
        <Poptip confirm transfer
          title="你确定要删除吗？"
          @on-ok="ok(row)"
          v-if="hasPermission('moms:pay:accountdelete')"
          style="text-align: left">
          <i class="iconsys icondel"
            title="删除"></i>
        </Poptip>
        <Button type="primary" size="small" @click="payValid(row)">支付验证</Button>
      </template>
    </Table>
    <Row type="flex">
      <Col span="12"
        class="module-menu-nav">
      </Col>
      <Col span="12">
        <div class="page-box">
          <Page :total="total"
            :page-size="pageSize"
            :current="pageIndex"
            show-total
            show-sizer
            @on-change="changePageIndex"
            @on-page-size-change="changePageSize" />
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import serviceMixins from '../mixins/serviceType'
import accountTypeMixins from '../mixins/accountType'
import { getAccountLists, getAccountChildren, deleteAccount, updateAccountVerify, paymentVerify } from '@/api/pay/account.js'
export default {
  name: 'payment_account_list',
  mixins: [serviceMixins, accountTypeMixins],
  data () {
    return {
      tableHeight: 0,
      accountName: '',
      serviceName: '-1',
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      loading: true,
      data: [],
      columns: [
        {
          type: 'selection',
          width: 60,
          fixed: 'left',
          align: 'center'
        },
        {
          title: '编号',
          fixed: 'left',
          slot: 'accountNo',
          width: 160
        },
        {
          title: '名称',
          key: 'accountName',
          minWidth: 120
        },
        {
          title: '商户名称',
          key: 'merchantName',
          minWidth: 150
        },
        {
          title: '法人代表',
          key: 'legalPerson',
          width: 120,
          align: 'center'
        },
        {
          title: '账户类型',
          slot: 'bankAccountType',
          width: 100,
          align: 'center'
        },
        {
          title: '开户银行',
          key: 'settlementBank',
          minWidth: 100
        },
        {
          title: '开户行名称',
          key: 'bankName',
          minWidth: 150
        },
        {
          title: '银行卡号',
          key: 'cardNo',
          width: 180
        },
        {
          title: '支付服务商',
          key: 'providerName',
          width: 100,
          align: 'center'
        },
        {
          title: '创建时间',
          key: 'createdAt',
          width: 150
        },
        {
          title: '操作',
          slot: 'action',
          fixed: 'right',
          width: 200
        }
      ],
      selections: []
    }
  },
  mounted () {
    this.getData()
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  watch: {
    '$route' (newRoute) {
      const poptips = document.querySelectorAll('body .ivu-poptip-popper.ivu-poptip-confirm.v-transfer-dom')
      poptips.forEach(poptip => {
        if (poptip.style.display !== 'none') poptip.style.display = 'none'
      })
      if (newRoute.name === 'payment_account_list') {
        this.search()
      }
    }
  },
  methods: {
    payValid (row) {
      this.$Spin.show({
        render: (h) => {
          return h('div', [
            h('Icon', {
              'class': 'demo-spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 18
              }
            }),
            h('div', 'Loading')
          ])
        }
      })
      paymentVerify({
        paymentAccountId: row.paymentAccountId
      }).then(res => {
        this.$Spin.hide()
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('支付验证成功')
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Spin.hide()
        this.$Message.error(`${err}`)
      })
    },
    filterSpace () {
      this.accountName = this.accountName.replace(/\s+/g, '')
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    reset () {
      this.accountName = ''
      this.serviceName = '-1'
      this.search()
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    addChildren () {
      if (this.selections.length !== 1) {
        this.$Message.error('请选择一个微信商户主账号')
      } else {
        const row = this.selections[0]
        if (row.parentId || row.providerCode !== 'weixin') {
          this.$Message.error('请选择正确的微信商户主账号')
        } else {
          this.$router.push({
            name: 'payment_account_create_child',
            params: {
              id: row.paymentAccountId
            },
            query: {
              isChild: 1
            }
          })
        }
      }
    },
    getData () {
      const params = {
        merchantName: this.accountName,
        providerName: this.serviceName === '-1' ? '' : this.serviceName,
        merchantId: this.merchantId,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize,
        deleted: 0,
        isParent: true
      }
      this.loading = true
      this.tableHeight = 0
      getAccountLists(params).then(res => {
        this.loading = false
        const result = res.data || {}
        this.selections = []
        if (result.status === 200) {
          this.data = result.data || []
          this.total = result.totalCount || 0
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
          this.renderStripe()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    skipAdd () {
      this.$router.push({
        name: 'payment_account_create'
      })
    },
    look (id) {
      this.$router.push({
        name: 'payment_account_detail',
        params: {
          id
        }
      })
    },
    skipEdit (row) {
      updateAccountVerify({
        merchantId: this.merchantId,
        paymentAccountId: row.paymentAccountId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$router.push({
            name: 'payment_account_edit',
            params: {
              id: row.paymentAccountId
            },
            query: {
              isChild: row.parentId ? 1 : 0,
              isEdit: 1
            }
          })
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    ok (row) {
      deleteAccount({
        merchantId: this.merchantId,
        paymentAccountId: row.paymentAccountId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    selectionChange (selections) {
      this.selections = selections
    },
    expandRow (row, index) {
      if (row.hasChildren) {
        if (row.isExpand) {
          this.changeData(row, index)
        } else {
          this.loading = true
          getAccountChildren({
            parentId: row.paymentAccountId,
            merchantId: this.merchantId,
            deleted: 0
          }).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.loading = false
              const rowClassName = this.getClassName(index)
              row.children = (result.data || []).map(item => ({
                ...item,
                rowClassName
              }))
              this.changeData(row, index)
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.$Message.error(`${err}`)
          })
        }
      }
    },
    changeData (row, index) {
      if (row.children) {
        if (row.isExpand) {
          this.data[index] = { ...row, isExpand: false }
          this.data = this.data.filter((item, index) => item.parentId !== row.paymentAccountId)
        } else {
          this.data[index] = { ...row, isExpand: true }
          this.data.splice(index + 1, 0, ...row.children)
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
        }
      }
    },
    rowClassName (row) {
      return row.rowClassName || ''
    },
    renderStripe () {
      this.data.forEach((item, index) => {
        item.rowClassName = this.getClassName(index)
      })
    },
    getClassName (index) {
      return index % 2 === 1 ? 'table-strip-info-row' : 'table-strip-row'
    },
    getEnumsName (value, enums) {
      const result = enums.filter(item => item.value === value)
      return result[0] ? result[0].label : ''
    }
  }
}
</script>

<style lang="less">
.payment_center_account {
  .search-box {
    .search-item-left {
      width: 70%;
    }
    .search-item-right {
      width: 30%;
    }
  }
  .table-icon-container {
    position: relative;
    left: -12px;
    cursor: pointer;
    .table-icon {
      position: relative;
      bottom: 1px;
    }
  }
  .table-strip-row td {
    background-color: #fff
  }
  .table-strip-info-row td {
    background-color: #f8f8f9
  }
  .ivu-table-tip {
    span {
      position: absolute;
      width: 100px;
      left: 50%;
      margin-left: -50px;
    }
  }
}
</style>
